#!/bin/bash

# See 0.pv-ts.problem script and its description for problem statement.
# 1.pv-ts.exec and 2.pv-ts.dos2unix.log-fix contains two sub-steps of resolution with detailed description.
# 3.pv-ts.solution have good full solution, but still have some drawbacks: pv output buferred and possibly that is not needed on terminal as plain text
# That script (idea got from https://stackoverflow.com/questions/40877384/jenkins-how-to-see-progress-in-the-log-output-when-it-gets-constantly-overwrit/48815760#48815760) should not have any mentioned drawbacks,
# but looks very cumbersome on my mind!

 # Link file descriptor #6 with stderr (saves "raw" stderr) - we will use it in interractive pv output:
exec 6>&2
_log_file="$(basename $0).$(date --iso-8601=s).log"
# Descriptor 7 will be used for base script output (stdout, stderr will be redirected here). We may apply there desired transformations like time line prepending
exec 7> >( ts '%d-%H:%M:%.S' | ts -i -- '+%H:%M:%.S' | tee -i -- "${_log_file}" )
# Descriptor 8 writes in the same log file, but bypass stderr and stdout!! That is for the case we want separate log and interractive terminal data representation
exec 8> >( ts '%d-%H:%M:%.S' | ts -i -- '+%H:%M:%.S'          >> "${_log_file}" )
exec 1>&7 2>&7


echo Hi

# Bytes:
SIZE=5000
SPEED=100

# Note. pv format increased to be longer for demonstrate output buffering. Run that and note as appeared parts of log
dd if=/dev/urandom bs=1 count=$SIZE | pv -s $SIZE --name=RawArchive --force -w $[ $(tput cols) - 35 ] -W -F'%N [%b]; Speed: %r; AVGspeed: %a; Elapsed: %t; %e; %p' -L $SPEED \
	2> >( tee /dev/stderr 2>&6 | stdbuf -eL -oL tr '\r' '\n' >&8 ) \
	> /dev/null

echo Bye
sleep 1
echo Bye
